/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.redis.service.RedisCache;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.util.StringUtil;
import com.je.meta.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021-08-05 13:55
 * @description:
 */
@RestController
@RequestMapping(value = "/je/meta/excel")
public class ExcelController extends AbstractPlatformController {

    private static final String EXCEL_DOWNLOAD_KEY = "excelDownloadKeys";

    @Autowired
    private Environment environment;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ExcelService excelService;

    /**
     * 表格数据导出
     * @param param
     */
    @RequestMapping(value = "/exp",method = RequestMethod.GET)
    public File exp(BaseMethodArgument param, HttpServletRequest request) {
        //获取全部参数
        String key = getStringParameter(request,"key");
        key = String.format("%s_%s", EXCEL_DOWNLOAD_KEY, key);
        String dataStr = (String) redisCache.get(key);
        //测试普通导出
        //dataStr = "{\"title\":\"测试导出\",\"fileName\":\"测试导出_2022-04-14.xls\",\"orderSql\":\"\",\"docFolderId\":\"\",\"funcId\":\"bjbTedm4lywLz7NMFib\",\"tableCode\":\"JE_TEST_EXCEL\",\"funcCode\":\"JE_TEST_EXCEL\",\"whereSql\":\" AND JE_TEST_EXCEL_ID IN ('1','2')\",\"j_query\":{\"custom\":[{\"type\":\"in\",\"code\":\"JE_TEST_EXCEL_ID\",\"value\":[\"1\",\"2\"]}]},\"styleType\":\"GRID\"}";
        //测试模板导出
        //dataStr = "{\"title\":\"测试模板导出\",\"fileName\":\"测试模板导出_2022-04-16.xlsx\",\"orderSql\":\" \",\"docFolderId\":\"\",\"funcId\":\"bjbTedm4lywLz7NMFib\",\"tableCode\":\"JE_TEST_EXCEL\",\"funcCode\":\"JE_TEST_EXCEL\",\"whereSql\":\" AND JE_TEST_EXCEL_ID IN ('1','2')\",\"j_query\":{\"custom\":[{\"type\":\"in\",\"code\":\"JE_TEST_EXCEL_ID\",\"value\":['1','2']}]},\"styleType\":\"TEMPLATE\",\"sheetId\":\"b390655013c744148235fb4334334f25\"}";
        //获取参数集
        JSONObject params = JSONObject.parseObject(dataStr);
        //参数赋值
        String tableCode = params.getString("tableCode");
        String funcId = params.getString("funcId");
        String fileName = params.getString("fileName");

        String queryType = params.getString("queryType");
        String procedureName = params.getString("procedureName");
        String dbSql = params.getString("dbSql");

        if ("procedure".equals(queryType) || "iditprocedure".equals(queryType)) {
            if (StringUtil.isEmpty(procedureName) || StringUtil.isEmpty(funcId)) {
                throw new PlatformException("存储过程名未传入", PlatformExceptionEnum.JE_CORE_EXCEL_PROCEDURE_ERROR, request);
            }
        } else if ("sql".equals(queryType)) {
            if (StringUtil.isEmpty(dbSql) || StringUtil.isEmpty(funcId)) {
                throw new PlatformException("自定义sql未传入", PlatformExceptionEnum.JE_CORE_EXCEL_DIYSQL_ERROR, request);
            }
        } else {
            if (StringUtil.isEmpty(tableCode) || StringUtil.isEmpty(funcId)) {
                throw new PlatformException("功能表名未传入", PlatformExceptionEnum.JE_CORE_EXCEL_TABLECODE_ERROR, request);
            }
        }
        try {
            //导出Excel
            InputStream inputStream = excelService.exportExcel(params,request);
            String defaultDirectory = environment.getProperty("servicecomb.downloads.directory");
            FileUtil.writeFromStream(inputStream,defaultDirectory + File.separator + fileName);
            return new File(defaultDirectory + File.separator + fileName);
        } catch (Exception e) {
            throw new PlatformException("新版导出Excel出错了", PlatformExceptionEnum.JE_CORE_EXCEL_EXP_ERROR, request, e);
        }
    }

    /**
     * 无窗口直接导入数据
     */
    /*@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult uploadFile(HttpServletRequest request) {
        //获取文件唯一标识
        String fileKey = getStringParameter(request,"fileKey");
        if (StringUtil.isNotEmpty(fileKey)) {
            String groupCode = getStringParameter(request,"groupCode");
            DynaBean group = metaResourceService.selectOneByNativeQuery("JE_CORE_EXCELGROUP",NativeQuery.build().applyWithParams(" GROUPCODE={0}", groupCode));
            if (group == null) {
                return BaseRespResult.errorResult("请执行保存后再上传文件!");
            }
            //导入数据
            JSONObject returnObj = excelService.impData(groupCode, fileKey, request);
            // 删除文件
            documentBusRpcService.delFilesByKey(Lists.newArrayList(fileKey), SecurityUserHolder.getCurrentAccountRealUserId());
            if (returnObj.containsKey("error")) {
                return BaseRespResult.errorResult(returnObj.getString("error"));
            } else {
                return BaseRespResult.successResult(returnObj);
            }
        } else {
            return BaseRespResult.errorResult("文件上传失败!");
        }
    }*/


}
